<template>
  <view class="relayTheMessage">
		<z-paging ref="paging" v-model="dataList" @query="queryList" auto-show-system-loading :loading-more-enabled="toBottomUpdate">
			<template #top>
				<z-tabs :list="tabList" @change="tabsChange"/>
				<view class="top-wrap">
					<up-input
						placeholder="请输入内容"
						border="surround"
						v-model="keyword"
						@change="searchchange"
					  :customStyle="{
					    width: '90vw',
							margin: '0 auto'
					  }"
					></up-input>
				</view>
			</template>
			<view class="container-relay">
				<view v-for="(item, index) in dataList" :key="item.id">
				  <view class="list-item" @click="forwardingTime(item)">
						<view class="avatar">
						  <up-image v-if="item.isGroup === 0 || tabsIndex == 1" :src="setUserImg(item)" width="82rpx" height="82rpx" radius="8rpx">
						    <template #error>
						      <text>{{ showUserName(item.username) }}</text>
						    </template>
						  </up-image>
							<group-avatar v-else :chat="item" :groupname="item.group_name"></group-avatar>
						</view>
						<viwe class="user-name">
							{{item.username || item.group_name}}
						</viwe>
					</view>
				</view>
			</view>
		</z-paging>

    <u-modal :show="show" :showConfirmButton='false' negativeTop="-10">
      <view class="slot-content">
				<view class="title">发送给：</view>
				<view class="to">
					<view class="avatar">
					  <up-image v-if="select.isGroup === 0 || tabsIndex == 1" :src="setUserImg(select)" width="82rpx" height="82rpx" radius="8rpx">
					    <template #error>
					      <text>{{ showUserName(select.username) }}</text>
					    </template>
					  </up-image>
						<group-avatar v-else :chat="select" :groupname="select.group_name"></group-avatar>
					</view>
					<view class="name">
						{{select.username || select.group_name}}
					</view>
				</view>
				<view class="modal-btn">
					<up-button @click="cancel" :customStyle="customStyle" type="primary" :hairline="false" :plain="true" text="取消"></up-button>
					<up-button @click="send" :customStyle="customStyle" type="primary" :hairline="false" :plain="true" text="确定"></up-button>
				</view>
      </view>
    </u-modal>
  </view>
</template>

<script>
import { getCurrentInstance } from 'vue'
import { chatApi } from '@/apis/cloud/chat';
import { useUserStore } from '@/pinia-store/user'
import { objectToFormData, processImageUrl } from "@/utils/chat"
import { mapStores } from 'pinia'
import GroupAvatar from '../../list/GroupAvatar.vue'
const AvaterBaseUrl = "https://cloud.mfarmers.com/dist/interface/public/upload/avatar/";

export default {
  name: 'relayTheMessage',
  components: {
    GroupAvatar,
  },
  data () {
    return {
      value: '',
			tabList: ['最近聊天','通讯录'],
      tabsIndex: 0,
      dataList: [],
			friends: [],
      keyword: '', // 搜索关键字
      timer: null, // 用来做防抖
      userInfo: {}, // 用户信息
      imInfo: {},
			toBottomUpdate: false,
			show: false,
			groupId: null,
			id: null,
			type: null,
			select: null,
			customStyle: {
				border: 'none',
				width: '50px',
				margin: 0
			}
    }
  },
  computed: {
    ...mapStores(useUserStore),
  },
  created () {
    this.userInfo = this.userStore.user;
		this.imInfo = JSON.parse(uni.getStorageSync('imInfo'));// 当前登录用户
  },
	onLoad(options) {
		console.log('转发参数', options);
		this.type = options.type;
		this.id = options.id;
		if(options.type == 2) {
			this.groupId = options.groupId;
		}
	},
  methods: {
		cancel() {
			this.show = false;
		},
		async send() {
			const params = {
			  'data[msgId]': this.id,
			  'data[originType]': this.type == 1 ? 'friend' : 'group',
			  'data[postType]': (!this.select.isGroup || this.select.isGroup === 0) ? 'friend' : 'group',
			  'data[postTo]': (!this.select.isGroup || this.select.isGroup === 0) ? (this.select.friend_account || this.select.account) : this.select.group_id,
				'data[sender]': this.imInfo.account,
				'data[token]': this.userInfo.token,
				'data[account]': this.imInfo.account,
			  url: 'index.php/users/message/forward-message'
			}

			const msg = await chatApi(this.userInfo.token, params);

			if(msg.code == 200) {
				this.show = false;
				uni.showToast({
					icon: 'none',
					duration: 1500,
					title: `已转发到 ${this.select?.group_name || this.select?.username}`
				})
				setTimeout(() => {
					uni.navigateBack();
				}, 1600)
			}else {
				uni.showToast({
					icon: 'none',
					duration: 1500,
					title: msg.message
				})
			}
		},
		tabsChange(index) {
			this.toBottomUpdate = index === 0 ? false : true;
			this.tabsIndex = index;
			this.$refs.paging.reload();
		},
		async queryList(pageNo, pageSize) {
			let msg = null;
			if(this.tabsIndex == 0) {
				const params = {
				  data: {
				    account: this.userInfo.chat_account,
				    token: this.userInfo.token,
				    uid: JSON.parse(uni.getStorageSync('imInfo')).id,
				  },
				  // url: 'index.php/users/Index/getMyTree'
					url: 'index.php/users/Index/getChatListCached'
				}
				msg = await chatApi(this.userInfo.token, objectToFormData(params));
			}else {
				const params = {
				  'data[keywords]': this.keyword,
				  'data[pageSize]': 20,
				  'data[page]': pageNo,
				  url: 'index.php/users/Member/getList'
				}
				msg = await chatApi(this?.userInfo?.token || token, params);
			}

			if (msg.code == 200) {
				const cache = this.tabsIndex == 0 ? msg.data.friends : msg.data.data;
				if(this.tabsIndex == 0) {
					cache.forEach(item => {
						if(item.isGroup == 1 && item.group_avatar_img != '') {
							item.groupAvatarImg = JSON.parse(item.group_avatar_img);
						}
					})
					this.friends = JSON.parse(JSON.stringify(cache))
					this.$refs.paging.complete(this.filteredMessageList());
				}else {
					this.$refs.paging.complete(cache);
				}
			}else {
				this.$refs.paging.complete(false);
			}
		},
    setUserImg (item) {
      return AvaterBaseUrl + (item.friend_phone || item.phone) + '.jpg'
    },
    // 输入框
    searchchange (e) {
      this.keyword = e;
      // 防抖处理
      if(this.tabsIndex == 1) {
      	clearTimeout(this.timer);
      	this.timer = setTimeout(() => {
      	  this.$refs.paging.reload();
      	}, 200);
      }else {
				this.filteredMessageList();
			}
    },
		filteredMessageList () {
		  if (!this.keyword) {
		    this.dataList = this.friends;
		  }
		  const kw = this.keyword.toLowerCase()
		  const cache = this.friends.filter(item => {
		    const name = (item.username || item.group_name || '').toLowerCase()
		    return name.includes(kw)
		  })

			this.dataList = cache;
			return cache;
		},
    // 通讯录选中
    forwardingTime(record) {
			this.select = record;
			console.log(record)
			this.show = true;
    },
    // 名称超长处理
    showUserName (username) {
      if (username && username.length > 2) {
        return username.substr(1, 2);
      } else {
        return username;
      }
    },
  }
}
</script>


<style lang="scss" scoped>
.top-wrap {
	position: relative;
	margin-top: 4px;
}
.relayTheMessage {
  width: 100%;
  background-color: #ffffff;
	::v-deep .u-modal__content {
		justify-content: start !important;
		padding-bottom: 8px !important;
		padding-right: 12px !important;
	}
}
.container-relay {
	padding: 10px 12px;
}
.list-item:active {
	background-color: #efefef;
}
.list-item {
	display: flex;
	align-items: center;
	margin-bottom: 8px;
	height: 90rpx;
	.avatar {
		width: 82rpx;
		height: 82rpx;
		text {
			width: 82rpx;
			height: 82rpx;
			text-align: center;
			line-height: 82rpx;
			font-size: 14px;
		}
	}
	.user-name {
		flex: 1;
		height: 100%;
		line-height: 90rpx;
		margin-left: 14px;
		border-bottom: 1rpx solid rgba(0, 0, 0, .05);
	}
}
.slot-content {
	width: 100%;
	.title {
		font-size: 16px;
	}
}
.to {
	display: flex;
	margin-top: 10px;
	align-items: center;
	color: rgba(0, 0, 0, .8);
	.name {
		margin-left: 10px;
	}
}
.modal-btn {
	width: 100%;
	display: flex;
	justify-content: end;
	margin-top: 14px;
}
</style>
